package cn.bdqn.layui.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CADM implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication,
                       Object o,
                       Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException {
        //collection里面存放着CustomFilterInvocationSecurityMetadataSource过滤出来的角色
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        for (ConfigAttribute configAttribute : collection){
            //判断你的路径在数据库中具不具备角色
            //判断你是不是匿名用户
            if("ROLE_LOGIN".equals(configAttribute.getAttribute())
                    && authentication instanceof UsernamePasswordAuthenticationToken){
                return;
            }
            //Authentication这里面存放着用户登录后的所有信息
            for (GrantedAuthority grantedAuthority : authorities){
                //判断路径需要的角色和用户所拥有的角色作比较
                if(grantedAuthority.getAuthority().equals(configAttribute.getAttribute())){
                    return;
                }
            }
        }
        throw  new AccessDeniedException("权限不足");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
